# #! -*- coding:utf-8 -*-
#!/usr/bin/python
#send template msg to sickers
#loop until ..

import pymongo
import codecs,sys,time
import json
import urllib
import urllib2
from pymongo import MongoClient

reload(sys)
sys.setdefaultencoding('utf-8')

conn = MongoClient("6dutcm.com",27017)
db = conn.health
db.authenticate("hou","hou@123")

MCH_ID = "1288388201"
APPID = "wx04b131310109a07c"
SECRETKEY = "d41dd4c033f4531b25ab3409390fb6e8"
APIKEY = "d41dd4c033f4531b25ab3409390fb6e8"


def get_token():
    url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"
    url=url.replace("APPID",APPID).replace("APPSECRET",SECRETKEY)
    #jdata = json.dumps(values)  # 对数据进行JSON格式化编码
    req = urllib2.Request(url) #, jdata)  # 生成页面请求的完整数据
    response = urllib2.urlopen(req)  # 发送页面请求
    retstr= response.read()
    return json.loads(retstr)["access_token"]

def post_json(sicker,msgid):
    template_id = "6i_Z4UKnMBlBi__yWdTIXdIC7VZNcSnUiVUZfxUv4iI";
    url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN"
    content = db.doctormsg.find_one({'uuid':msgid})
    if any(content):
        txt=sicker["name"]+":"+content["msg"]
    token = get_token()
    url = url.replace("ACCESS_TOKEN", token)
    values = {
        "touser": sicker["wxid"],
        "template_id": template_id,
        "url": "http://6dutcm.com/health/wx/doctordetail?id="+content["doctorId"],
        "data": {
            "first": {
                "value": txt,
                "color": "#173177"
            },
            "keyword1": {
                "value": "医生最新通知",
                "color": "#996666"
            },
            "keyword2": {
                "value": sicker["name"],
                "color": "#428bca"
            },
            "keyword3": {
                "value": content["createtime"],
                "color": "#777777"
            },
            "remark": {
                "value": "点击详情进入医生个人主页！",
                "color": "#777777"
            }
        }
    }

    jdata = json.dumps(values)  # 对数据进行JSON格式化编码
    req = urllib2.Request(url, jdata)  # 生成页面请求的完整数据
    response = urllib2.urlopen(req)  # 发送页面请求
    return response.read()

def msg_to_sicker(sickerId,msgId):
    print "send to:",sickerId
    user = db.user.find_one({'userId':sickerId})
    if any(user):
        post_json(user,msgId)
    #url = 'http://6dutcm.com/health/wx/sendmsg?sickerId='+sickerId+"&msgId="+msgId
    #ret = urllib2.urlopen(url).read()
    #values = {"sickerId":sickerId, "msgId":msgId}
    #params = json.dumps(values)
    #headers = {"Content-type": "application/json", "Accept": "application/json"}
    #req = urllib2.Request(url, params, headers)
    #response = urllib2.urlopen(req)
    #ret=response.read()
    #s = json.loads(ret)
    #print s.keys()

def handle_one(msgId,doctorId):
    fans = db.attention.find({'targetId': doctorId})
    for fan in fans:
        sickerId = fan["userId"]
        msg_to_sicker(sickerId,msgId)
        time.sleep(0.1)
    #call restful to send msg to sicker
    db.doctormsg.update({'uuid':msgId}, {'$set': {'sended':1}})


def one_loop():
    contents = db.doctormsg.find({'sended':0})
    for record in contents:
        msgId = record["uuid"]
        doctorId=record['doctorId']
        handle_one(msgId,doctorId)
        time.sleep(1)

if __name__ == '__main__':
    print "do_msg starting..."
    while True:
        #print "one loop"
        one_loop()
        time.sleep(2)
    #msg_to_sicker("13851821623","6166503ac79845ddb3ec3617097082d3")






